package com.mall.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mall.service.CommodityService;
import com.mall.service.SeckillService;

@Service
public class SeckillThread implements Runnable {
	private static Map<Integer, Date> datemap = new HashMap<Integer, Date>();
	private static Map<Integer, Date> enddatemap = new HashMap<Integer, Date>();
	private static Map<Integer, Integer> countnum = new HashMap<Integer, Integer>();
	private static List<Integer> idlist = new ArrayList<Integer>();
	private static Integer counter = 1;
	@Autowired
	private CommodityService commoditeService;
	@Autowired
	private SeckillService seckillService;

	public static void setTimeAndId(Date startdate, Integer id, Integer num, Date edate) {
		datemap.put(id, startdate);
		countnum.put(id, num);
		idlist.add(id);
		enddatemap.put(id, edate);
	}

	@Override
	public void run() {
		while (true) {
			// 容器启动之后第二次循环,检查数据库中的秒杀添加到列队,清除过期和已完成的秒杀任务
			if (counter == 2) {
				seckillService.update();
				List<com.mall.model.Seckill> listAndUpdate = seckillService.listAndUpdate();
				for (com.mall.model.Seckill s : listAndUpdate) {
					setTimeAndId(s.getSdate(), s.getId(), s.getCountnum(), s.getEdate());
				}
			}
			// 每1小时清理一次过期任务
			if ((counter % 720) == 0) {
				seckillService.update();
			}
			//每2分钟获取一次首页数据写入redis
			if ((counter % 24) == 0) {
				try {
					commoditeService.commListToRedis();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			Date now = new Date();
			if (idlist.size() != 0) {
				// 遍历id集合
				Iterator<Integer> iterator = idlist.iterator();
				while (iterator.hasNext()) {
					Integer id = iterator.next();
					Date date = datemap.get(id);
					Date edate = enddatemap.get(id);
					long endtime = edate.getTime() - now.getTime();
					if (endtime <= 0) {
						iterator.remove();
						datemap.remove(id);
						enddatemap.remove(id);
						break;
					}
					long time = date.getTime() - now.getTime();
					// 比较时间后,如果剩余时间小于1分钟,启动单独线程准备开启秒杀
					if (time < 60000l) {
						try {
							SeckillStart s = new SeckillStart(id, date, countnum.get(id));
							com.mall.util.Seckill.tpe.execute(s);
							// 删除已开启单独线程的商品id和date
							iterator.remove();
							datemap.remove(id);
							break;
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				counter = counter + 1;
			}

		}
	}

	public SeckillService getSeckillService() {
		return seckillService;
	}

	public void setSeckillService(SeckillService seckillService) {
		this.seckillService = seckillService;
	}

}
